package com.webex.ta.hydra.function;

import com.webex.ta.hydra.exceptions.InvalidVariableException;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: vegaz
 * Date: 2010-8-30
 * Time: 13:38:10
 * To change this template use File | Settings | File Templates.
 */
public class CompoundVariable extends AbstractFunction {

    private String rawParameter;

    private boolean hasFunction;

    private LinkedList compiledComponents = new LinkedList();

    public List<String> getArgumentDesc() {
		return EMTPY;
	}

    @Override
    public String execute() {
        if (compiledComponents == null || compiledComponents.size() == 0) {
			return ""; // $NON-NLS-1$
		}

		StringBuffer results = new StringBuffer();
        for (Object compiledComponent : compiledComponents) {
            if (compiledComponent instanceof Function) {
                results.append(((Function) compiledComponent).execute());
            } else if (compiledComponent instanceof SimpleVariable) {
                results.append(((SimpleVariable) compiledComponent).toString());
            } else {
                results.append(compiledComponent);
            }
        }

		return results.toString();
    }

    public void setParameters(Collection parameters) throws InvalidVariableException {
	}

    public String getReferenceKey() {
		return "";
	}

    public boolean hasFunction() {
		return hasFunction;
	}

    public String getRaw() {
        return rawParameter;
    }

    public CompoundVariable getFunction() {
		CompoundVariable func = new CompoundVariable();
		func.compiledComponents = (LinkedList) compiledComponents.clone();
		func.rawParameter = rawParameter;
		return func;
	}

    public void clear() {
		hasFunction = false;
		compiledComponents.clear();
	}

    public void setParameter(String param) throws InvalidVariableException {
        rawParameter = param;

        if (param == null || param.length() == 0) {
			return;
		}

		compiledComponents = FunctionParser.compileString(param);
		if (compiledComponents.size() > 1 || !(compiledComponents.get(0) instanceof String)) {
			hasFunction = true;
		}
    }
}
